package com.learn.config;

import com.learn.utils.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @program: rmi
 * @description
 * @author: luffy
 * @create: 2020-08-17 21:28
 */
public class RpcDeCoder extends ByteToMessageDecoder {
    private Class<?> clazz;

    private Serializer serializer;

    public RpcDeCoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List list) throws Exception {
        if (byteBuf.readableBytes()>4) {
            byteBuf.markReaderIndex();
            int dataLen = byteBuf.readInt();
            if (dataLen <0) {
                channelHandlerContext.close();
            }
            if (byteBuf.readableBytes() < dataLen) {
                byteBuf.resetReaderIndex();
                return;
            }
            byte[] body = new byte[dataLen];

            byteBuf.readBytes(body);

            Object o = serializer.deserialize(clazz, body);
            list.add(o);
        }
    }

}
